<template>
    <div class="order-container">
        <h2>新增销售订单</h2>

        <vxe-form ref="orderForm" :model="orderInfo" :rules="orderRules" size="medium" label-width="120px">
            <!-- 订单基本信息 -->
            <div class="form-section">
                <h3>订单基本信息</h3>
                <vxe-row :gutter="20">
                    <vxe-col :span="6">
                        <vxe-form-item field="orderNo" label="订单编号" :span="24">
                            <vxe-input v-model="orderInfo.orderNo" placeholder="自动生成" disabled></vxe-input>
                        </vxe-form-item>
                    </vxe-col>
                    <vxe-col :span="6">
                        <vxe-form-item field="orderDate" label="订单日期" :span="24">
                            <vxe-date-picker v-model="orderInfo.orderDate" type="date" placeholder="选择日期"></vxe-date-picker>
                        </vxe-form-item>
                    </vxe-col>
                    <vxe-col :span="6">
                        <vxe-form-item field="customerName" label="客户名称" :span="24">
                            <vxe-select v-model="orderInfo.customerName" placeholder="选择客户">
                                <vxe-option v-for="item in customerList" :key="item.id" :label="item.name" :value="item.name"></vxe-option>
                            </vxe-select>
                        </vxe-form-item>
                    </vxe-col>
                    <vxe-col :span="6">
                        <vxe-form-item field="customerContact" label="联系人" :span="24">
                            <vxe-input v-model="orderInfo.customerContact" placeholder="输入联系人"></vxe-input>
                        </vxe-form-item>
                    </vxe-col>
                </vxe-row>

                <vxe-row :gutter="20">
                    <vxe-col :span="6">
                        <vxe-form-item field="customerPhone" label="联系电话" :span="24">
                            <vxe-input v-model="orderInfo.customerPhone" placeholder="输入联系电话"></vxe-input>
                        </vxe-form-item>
                    </vxe-col>
                    <vxe-col :span="6">
                        <vxe-form-item field="deliveryAddress" label="送货地址" :span="24">
                            <vxe-input v-model="orderInfo.deliveryAddress" placeholder="输入送货地址"></vxe-input>
                        </vxe-form-item>
                    </vxe-col>
                    <vxe-col :span="6">
                        <vxe-form-item field="paymentType" label="付款方式" :span="24">
                            <vxe-select v-model="orderInfo.paymentType" placeholder="选择付款方式">
                                <vxe-option label="微信支付" value="wechat"></vxe-option>
                                <vxe-option label="支付宝" value="alipay"></vxe-option>
                                <vxe-option label="银行转账" value="bank"></vxe-option>
                                <vxe-option label="货到付款" value="cod"></vxe-option>
                            </vxe-select>
                        </vxe-form-item>
                    </vxe-col>
                    <vxe-col :span="6">
                        <vxe-form-item field="orderStatus" label="订单状态" :span="24">
                            <vxe-select v-model="orderInfo.orderStatus" placeholder="选择状态" disabled>
                                <vxe-option label="待审核" value="pending"></vxe-option>
                                <vxe-option label="已审核" value="approved"></vxe-option>
                                <vxe-option label="已取消" value="cancelled"></vxe-option>
                            </vxe-select>
                        </vxe-form-item>
                    </vxe-col>
                </vxe-row>

                <vxe-row>
                    <vxe-col :span="24">
                        <vxe-form-item field="remark" label="订单备注" :span="24">
                            <vxe-textarea v-model="orderInfo.remark" placeholder="输入订单备注信息" rows="3"></vxe-textarea>
                        </vxe-form-item>
                    </vxe-col>
                </vxe-row>
            </div>

            <!-- 商品明细 -->
            <div class="form-section">
                <div class="section-header">
                    <h3>商品明细</h3>
                    <vxe-button type="primary" @click="addProduct">
                        <i class="vxe-icon vxe-icon-plus"></i> 添加商品
                    </vxe-button>
                </div>

                <vxe-grid
                    ref="productGrid"
                    :data="orderProducts"
                    :columns="productColumns"
                    :edit-config="{trigger: 'click', mode: 'row'}"
                    border
                    show-footer
                >
                    <template #footer>
                        <tr>
                            <td colspan="5" align="right">
                                <strong>合计金额：</strong>
                                <span class="total-amount">¥{{ totalAmount.toFixed(2) }}</span>
                            </td>
                        </tr>
                    </template>
                </vxe-grid>
            </div>

            <!-- 操作按钮 -->
            <div class="form-actions">
                <vxe-button type="primary" @click="submitOrder">提交订单</vxe-button>
                <vxe-button @click="resetForm">重置</vxe-button>
                <vxe-button type="warning" @click="cancelOrder">取消</vxe-button>
            </div>
        </vxe-form>
    </div>
</template>

<script>
export default {
    data() {
        return {
            // 订单基本信息
            orderInfo: {
                orderNo: '',
                orderDate: new Date(),
                customerName: '',
                customerContact: '',
                customerPhone: '',
                deliveryAddress: '',
                paymentType: '',
                orderStatus: 'pending',
                remark: ''
            },

            // 订单商品列表
            orderProducts: [
                { id: 1, productName: '', specification: '', unit: '', price: 0, quantity: 1, amount: 0 }
            ],

            // 客户列表
            customerList: [
                { id: 1, name: '北京某某科技有限公司' },
                { id: 2, name: '上海某某贸易有限公司' },
                { id: 3, name: '广州某某实业有限公司' },
                { id: 4, name: '深圳某某发展有限公司' }
            ],

            // 商品列配置
            productColumns: [
                { type: 'seq', title: '序号', width: 80 },
                {
                    field: 'productName',
                    title: '商品名称',
                    editRender: {
                        name: 'vxe-select',
                        props: {
                            options: [
                                { label: '笔记本电脑', value: '笔记本电脑' },
                                { label: '智能手机', value: '智能手机' },
                                { label: '平板电脑', value: '平板电脑' },
                                { label: '智能手表', value: '智能手表' },
                                { label: '无线耳机', value: '无线耳机' }
                            ]
                        }
                    },
                    width: 200
                },
                {
                    field: 'specification',
                    title: '规格型号',
                    editRender: { name: 'vxe-input' },
                    width: 200
                },
                {
                    field: 'unit',
                    title: '单位',
                    editRender: { name: 'vxe-input' },
                    width: 100
                },
                {
                    field: 'price',
                    title: '单价(元)',
                    editRender: { name: 'vxe-input', props: { type: 'number', min: 0 } },
                    formatter: ({ cellValue }) => {
                        return cellValue.toFixed(2)
                    },
                    width: 120
                },
                {
                    field: 'quantity',
                    title: '数量',
                    editRender: { name: 'vxe-input', props: { type: 'number', min: 1 } },
                    width: 100
                },
                {
                    field: 'amount',
                    title: '金额(元)',
                    formatter: ({ cellValue }) => {
                        return cellValue.toFixed(2)
                    },
                    width: 120
                },
                {
                    title: '操作',
                    width: 120,
                    align: 'center',
                    fixed: 'right',
                }
            ],

            // 表单验证规则
            orderRules: {
                customerName: [
                    { required: true, message: '请选择客户名称', trigger: 'blur' }
                ],
                orderDate: [
                    { required: true, message: '请选择订单日期', trigger: 'change' }
                ],
                paymentType: [
                    { required: true, message: '请选择付款方式', trigger: 'change' }
                ]
            }
        }
    },

    computed: {
        // 计算总金额
        totalAmount() {
            return this.orderProducts.reduce((total, item) => {
                return total + item.amount
            }, 0)
        }
    },

    created() {
        // 生成订单编号
        this.generateOrderNo()
    },

    methods: {
        // 生成订单编号
        generateOrderNo() {
            const date = new Date()
            const year = date.getFullYear()
            const month = String(date.getMonth() + 1).padStart(2, '0')
            const day = String(date.getDate()).padStart(2, '0')
            const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0')
            this.orderInfo.orderNo = `SO${year}${month}${day}${random}`
        },

        // 添加商品
        addProduct() {
            const newId = this.orderProducts.length > 0
                ? Math.max(...this.orderProducts.map(item => item.id)) + 1
                : 1

            this.orderProducts.push({
                id: newId,
                productName: '',
                specification: '',
                unit: '',
                price: 0,
                quantity: 1,
                amount: 0
            })
        },

        // 删除商品
        deleteProduct(id) {
            this.orderProducts = this.orderProducts.filter(item => item.id !== id)
        },

        // 提交订单
        submitOrder() {
            this.$refs.orderForm.validate().then(valid => {
                if (valid) {
                    if (this.orderProducts.length === 0 || this.orderProducts.every(item => !item.productName)) {
                        this.$Message.warning('请添加至少一个商品')
                        return
                    }

                    // 这里可以添加提交订单的API调用逻辑
                    console.log('提交订单信息:', {
                        ...this.orderInfo,
                        products: this.orderProducts,
                        totalAmount: this.totalAmount
                    })

                    this.$Message.success('订单提交成功')
                }
            })
        },

        // 重置表单
        resetForm() {
            this.$refs.orderForm.resetFields()
            this.orderInfo.orderDate = new Date()
            this.orderInfo.orderStatus = 'pending'
        },

        // 取消订单
        cancelOrder() {
            if (window.confirm('确定要取消新增订单吗？已填写的内容将丢失')) {
                // 这里可以添加返回上一页的逻辑
                console.log('取消新增订单')
            }
        }
    },

    watch: {
        // 监听商品价格和数量变化，自动计算金额
        orderProducts: {
            deep: true,
            handler(products) {
                products.forEach(item => {
                    item.amount = item.price * item.quantity
                })
            }
        }
    }
}
</script>

<style scoped>
.order-container {
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.form-section {
    margin-bottom: 30px;
    padding: 15px;
    border: 1px solid #e8e8e8;
    border-radius: 4px;
}

.form-section h3 {
    margin-top: 0;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e8e8e8;
    color: #1890ff;
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.form-actions {
    margin-top: 20px;
    text-align: center;
}

.form-actions button {
    margin: 0 10px;
}

.total-amount {
    color: #f5222d;
    font-size: 16px;
}
</style>
